package vip.xiaonuo.issued.reactor;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.Reactor;
import reactor.event.Event;
import reactor.function.Consumer;
import vip.xiaonuo.facedoor.modular.device.entity.DeviceCategory;
import vip.xiaonuo.facedoor.modular.devicebase.entity.DeviceBase;
import vip.xiaonuo.facedoor.modular.devicebase.service.DeviceBaseService;
import vip.xiaonuo.facedoor.modular.memberdevice.constant.MemberDeviceConstant;
import vip.xiaonuo.facedoor.modular.memberdevice.entity.MemberDevice;
import vip.xiaonuo.facedoor.modular.memberdevice.service.MemberDeviceService;
import vip.xiaonuo.facedoor.modular.memberfeatures.entity.MemberFeatures;
import vip.xiaonuo.facedoor.modular.topic.EventTopic;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static reactor.event.selector.Selectors.$;

/**
 * 掌静脉特征值更新之后，
 * 同步修改其他设备上的特征值
 */
@Service
public class MemberPalmFeatureUpdateListener implements Consumer<Event<MemberFeatures>>, InitializingBean {

    @Resource
    private DeviceBaseService deviceBaseService;

    @Autowired
    private MemberDeviceService memberDeviceService;

    @Autowired
    private Reactor reactor;

    @Override
    public void afterPropertiesSet() throws Exception {
        reactor.on($(EventTopic.MEMBER_PALM_VALUE_UPDATE), this);
    }

    @Override
    public void accept(Event<MemberFeatures> event) {
        MemberFeatures memberFeatures = event.getData();

        List<DeviceBase> devices = deviceBaseService.list(new LambdaQueryWrapper<DeviceBase>().eq(DeviceBase :: getDeviceType , DeviceCategory.SUB_TYPE_STORE)
                .eq(DeviceBase :: getDeviceState, "1"));

        List<Long> deviceids = new ArrayList<>();

        devices.forEach( device -> {deviceids.add(device.getId());});

        List<MemberDevice> temps = memberDeviceService.list(new LambdaQueryWrapper<MemberDevice>()
                .eq(MemberDevice :: getMemberId ,memberFeatures.getDwMemberUserId())
                .in(MemberDevice :: getDeviceId , deviceids.toArray()));

        for (MemberDevice temp : temps) {
            if(ObjectUtil.equal(temp.getStatus(), MemberDeviceConstant.SYNC_SUCCESS )){
                temp.setStatus(MemberDeviceConstant.UPDATE);
            }else if(ObjectUtil.equal(temp.getStatus(), MemberDeviceConstant.UPDATE_FAIL )){
                temp.setFailReason("");
                temp.setStatus(MemberDeviceConstant.UPDATE);
            }else if(ObjectUtil.equal(temp.getStatus(), MemberDeviceConstant.ADD_FAIL )){
                temp.setFailReason("");
                temp.setStatus(MemberDeviceConstant.ADD);
            }
        }
        memberDeviceService.updateBatchById(temps);
    }
}
